import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  message,
  Card,
  Row,
  Col,
  Avatar,
  Popconfirm,
  Descriptions,
  Switch,
  Timeline
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UserOutlined,
  LockOutlined,
  SafetyOutlined,
  SearchOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { adminUserAPI, roleAPI } from '../../services/api';
import { useAdminAuth } from '../../hooks/useAuth';
import { encryptPassword } from '../../utils/auth';

const { Option } = Select;

const AdminUsers = () => {
  const [loading, setLoading] = useState(false);
  const [adminUsers, setAdminUsers] = useState([]);
  const [roles, setRoles] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [searchForm] = Form.useForm();
  const [userForm] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState(null);
  const [selectedUser, setSelectedUser] = useState(null);
  const { hasAdminPermission, user: currentUser } = useAdminAuth();

  // 统一的按钮样式
  const buttonStyle = {
    height: '32px',
    fontSize: '14px',
    fontWeight: '400',
    borderRadius: '6px'
  };

  useEffect(() => {
    loadAdminUsers();
    loadRoles();
  }, []);

  const loadAdminUsers = async (params = {}) => {
    setLoading(true);
    try {
      const response = await adminUserAPI.getAdminUsers({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...params
      });
      
      if (response.success) {
        setAdminUsers(response.data.list);
        setPagination(prev => ({
          ...prev,
          total: response.data.total
        }));
      }
    } catch (error) {
      message.error('加载管理员列表失败');
    } finally {
      setLoading(false);
    }
  };

  const loadRoles = async () => {
    try {
      const response = await roleAPI.getRoles();
      if (response.success) {
        setRoles(response.data);
      }
    } catch (error) {
      console.error('加载角色失败:', error);
    }
  };

  const handleSearch = () => {
    const values = searchForm.getFieldsValue();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadAdminUsers(values);
  };

  const handleReset = () => {
    searchForm.resetFields();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadAdminUsers();
  };

  const handleAdd = () => {
    setEditingUser(null);
    userForm.resetFields();
    userForm.setFieldsValue({
      status: 'active'
    });
    setModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingUser(record);
    userForm.setFieldsValue({
      ...record,
      roleIds: record.roles?.map(r => r.id) || []
    });
    setModalVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      const response = await adminUserAPI.deleteAdminUser(id);
      if (response.success) {
        message.success('删除成功');
        loadAdminUsers();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleResetPassword = (user) => {
    setSelectedUser(user);
    passwordForm.resetFields();
    setPasswordModalVisible(true);
  };

  const handleViewDetail = (user) => {
    setSelectedUser(user);
    setDetailModalVisible(true);
  };

  const handleStatusChange = async (userId, status) => {
    try {
      const response = await adminUserAPI.updateAdminUser(userId, { 
        status: status ? 'active' : 'disabled' 
      });
      if (response.success) {
        message.success(status ? '账号已启用' : '账号已禁用');
        loadAdminUsers();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await userForm.validateFields();
      
      if (!editingUser) {
        // 新增时密码必填，并加密
        values.password = encryptPassword(values.password);
      } else {
        // 编辑时如果没有输入密码，则不更新密码
        if (!values.password) {
          delete values.password;
        } else {
          values.password = encryptPassword(values.password);
        }
      }

      let response;
      if (editingUser) {
        response = await adminUserAPI.updateAdminUser(editingUser.id, values);
      } else {
        response = await adminUserAPI.addAdminUser(values);
      }

      if (response.success) {
        message.success(editingUser ? '更新成功' : '添加成功');
        setModalVisible(false);
        loadAdminUsers();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  const handlePasswordSubmit = async () => {
    try {
      const values = await passwordForm.validateFields();
      const encryptedPassword = encryptPassword(values.newPassword);
      
      const response = await adminUserAPI.resetPassword(selectedUser.id, encryptedPassword);
      if (response.success) {
        message.success('密码重置成功');
        setPasswordModalVisible(false);
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('密码重置失败');
    }
  };

  const columns = [
    {
      title: '管理员信息',
      key: 'userInfo',
      render: (_, record) => (
        <Space>
          <Avatar 
            size={40}
            src={record.avatar}
            icon={<UserOutlined />}
            style={{ backgroundColor: '#1890ff' }}
          />
          <div>
            <div style={{ fontWeight: 'bold' }}>{record.nickname || record.username}</div>
            <div style={{ fontSize: '12px', color: '#999' }}>{record.username}</div>
          </div>
        </Space>
      ),
    },
    {
      title: '角色',
      dataIndex: 'roles',
      key: 'roles',
      render: (roles) => (
        <Space wrap>
          {roles?.map(role => (
            <Tag key={role.id} color="blue">
              {role.name}
            </Tag>
          )) || '-'}
        </Space>
      ),
    },
    {
      title: '联系方式',
      key: 'contact',
      render: (_, record) => (
        <div>
          <div>{record.email || '-'}</div>
          <div style={{ fontSize: '12px', color: '#999' }}>{record.phone || '-'}</div>
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '正常' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginTime',
      key: 'lastLoginTime',
      render: (time) => time ? new Date(time).toLocaleString() : '从未登录',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time) => new Date(time).toLocaleDateString(),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 280,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EyeOutlined />}
            size="small"
            onClick={() => handleViewDetail(record)}
            style={buttonStyle}
          >
            查看
          </Button>
          
          {hasAdminPermission('admin:edit') && (
            <Button
              type="link"
              icon={<EditOutlined />}
              size="small"
              onClick={() => handleEdit(record)}
              style={buttonStyle}
            >
              编辑
            </Button>
          )}
          
          {hasAdminPermission('admin:reset') && (
            <Button
              type="link"
              icon={<LockOutlined />}
              size="small"
              onClick={() => handleResetPassword(record)}
              style={buttonStyle}
            >
              重置密码
            </Button>
          )}
          
          {hasAdminPermission('admin:disable') && record.username !== 'superadmin' && (
            <Switch
              size="small"
              checked={record.status === 'active'}
              onChange={(checked) => handleStatusChange(record.id, checked)}
            />
          )}
          
          {hasAdminPermission('admin:delete') && 
           record.username !== 'superadmin' && 
           record.id !== currentUser?.id && (
            <Popconfirm
              title="确定要删除这个管理员吗？"
              onConfirm={() => handleDelete(record.id)}
            >
              <Button
                type="link"
                danger
                icon={<DeleteOutlined />}
                size="small"
                style={buttonStyle}
              >
                删除
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="horizontal"
          onFinish={handleSearch}
        >
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item name="keyword" label="关键词">
                <Input placeholder="搜索用户名、昵称、邮箱" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="roleId" label="角色">
                <Select placeholder="选择角色" allowClear>
                  {roles.map(role => (
                    <Option key={role.id} value={role.id}>
                      {role.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="status" label="状态">
                <Select placeholder="选择状态" allowClear>
                  <Option value="active">正常</Option>
                  <Option value="disabled">禁用</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Space>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  icon={<SearchOutlined />}
                  style={buttonStyle}
                >
                  搜索
                </Button>
                <Button onClick={handleReset} style={buttonStyle}>重置</Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card
        title="管理员管理"
        extra={
          hasAdminPermission('admin:add') && (
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAdd}
              style={buttonStyle}
            >
              添加管理员
            </Button>
          )
        }
      >
        <Table
          columns={columns}
          dataSource={adminUsers}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize }));
              loadAdminUsers({ page, pageSize });
            },
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 添加/编辑管理员模态框 */}
      <Modal
        title={editingUser ? '编辑管理员' : '添加管理员'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={600}
        destroyOnClose
        okButtonProps={{ style: buttonStyle }}
        cancelButtonProps={{ style: buttonStyle }}
      >
        <Form
          form={userForm}
          layout="vertical"
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="username"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { pattern: /^[a-zA-Z0-9_]{3,20}$/, message: '用户名只能包含字母、数字和下划线，长度3-20位' }
                ]}
              >
                <Input 
                  placeholder="请输入用户名" 
                  disabled={!!editingUser}
                  prefix={<UserOutlined />}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="nickname"
                label="昵称"
                rules={[{ required: true, message: '请输入昵称' }]}
              >
                <Input placeholder="请输入昵称" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="password"
                label={editingUser ? '密码（留空不修改）' : '密码'}
                rules={editingUser ? [] : [
                  { required: true, message: '请输入密码' },
                  { min: 6, message: '密码至少6位' }
                ]}
              >
                <Input.Password 
                  placeholder={editingUser ? '留空不修改密码' : '请输入密码'}
                  prefix={<LockOutlined />}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="confirmPassword"
                label="确认密码"
                dependencies={['password']}
                rules={[
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value && !getFieldValue('password')) {
                        return Promise.resolve();
                      }
                      if (getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致'));
                    },
                  }),
                ]}
              >
                <Input.Password 
                  placeholder="请再次输入密码"
                  prefix={<LockOutlined />}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { type: 'email', message: '请输入有效的邮箱地址' }
                ]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="手机号"
                rules={[
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
                ]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="roleIds"
            label="角色"
            rules={[{ required: true, message: '请选择至少一个角色' }]}
          >
            <Select
              mode="multiple"
              placeholder="请选择角色"
            >
              {roles.map(role => (
                <Option key={role.id} value={role.id}>
                  {role.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
          >
            <Select>
              <Option value="active">正常</Option>
              <Option value="disabled">禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 重置密码模态框 */}
      <Modal
        title="重置密码"
        open={passwordModalVisible}
        onOk={handlePasswordSubmit}
        onCancel={() => setPasswordModalVisible(false)}
        width={400}
        destroyOnClose
        okButtonProps={{ style: buttonStyle }}
        cancelButtonProps={{ style: buttonStyle }}
      >
        <p>将为用户 <strong>{selectedUser?.nickname || selectedUser?.username}</strong> 重置密码</p>
        <Form
          form={passwordForm}
          layout="vertical"
        >
          <Form.Item
            name="newPassword"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码至少6位' }
            ]}
          >
            <Input.Password 
              placeholder="请输入新密码"
              prefix={<LockOutlined />}
            />
          </Form.Item>
          
          <Form.Item
            name="confirmPassword"
            label="确认密码"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password 
              placeholder="请再次输入新密码"
              prefix={<LockOutlined />}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 查看详情模态框 */}
      <Modal
        title="管理员详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)} style={buttonStyle}>
            关闭
          </Button>
        ]}
        width={700}
      >
        {selectedUser && (
          <div>
            <Descriptions bordered column={2} style={{ marginBottom: 24 }}>
              <Descriptions.Item label="用户名">{selectedUser.username}</Descriptions.Item>
              <Descriptions.Item label="昵称">{selectedUser.nickname}</Descriptions.Item>
              <Descriptions.Item label="邮箱">{selectedUser.email || '-'}</Descriptions.Item>
              <Descriptions.Item label="手机号">{selectedUser.phone || '-'}</Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={selectedUser.status === 'active' ? 'green' : 'red'}>
                  {selectedUser.status === 'active' ? '正常' : '禁用'}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="角色">
                <Space wrap>
                  {selectedUser.roles?.map(role => (
                    <Tag key={role.id} color="blue">{role.name}</Tag>
                  ))}
                </Space>
              </Descriptions.Item>
              <Descriptions.Item label="创建时间" span={2}>
                {new Date(selectedUser.createTime).toLocaleString()}
              </Descriptions.Item>
              <Descriptions.Item label="最后登录时间" span={2}>
                {selectedUser.lastLoginTime ? 
                  new Date(selectedUser.lastLoginTime).toLocaleString() : '从未登录'}
              </Descriptions.Item>
            </Descriptions>

            <h4>最近操作记录</h4>
            <Timeline>
              <Timeline.Item color="green">
                2024-01-15 14:30:00 - 登录系统
              </Timeline.Item>
              <Timeline.Item color="blue">
                2024-01-15 14:35:00 - 查看商品列表
              </Timeline.Item>
              <Timeline.Item color="blue">
                2024-01-15 14:40:00 - 编辑商品 "iPhone 15"
              </Timeline.Item>
              <Timeline.Item>
                2024-01-15 15:00:00 - 退出系统
              </Timeline.Item>
            </Timeline>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default AdminUsers; 